
<template>
  <div class="project-expenses">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="项目总经费" name="all"></el-tab-pane>
      <el-tab-pane label="年度开支" name="year"></el-tab-pane>
      <el-tab-pane label="季度开支" name="quarter"></el-tab-pane>
      <el-tab-pane label="月度开支" name="month"></el-tab-pane>
    </el-tabs>
    <div class="source-group">
      <template v-for="(item, index) in sourceGroup">
        <div :key="index" v-if="budget_from.includes(item.key) || item.key == 'XMJFLY_ZJF'"
          :class="{ 'is-active': activeSource == item.key }" @click="sourceHandleClick(item)">{{ item.name }}</div>
      </template>
    </div>
    <div v-if="activeName == 'all' && tableLoading">
      <vxe-table max-height="500" border resizable show-overflow :data="budgetList" size="mini" show-footer
        :footer-method="footerMethod" :merge-footer-items="[{ row: 0, col: 0, rowspan: 2, colspan: 2 }]">
        <vxe-column type="seq" width="60"></vxe-column>
        <vxe-column align="left" field="class_funds" title="科目名称"></vxe-column>
        <vxe-column align="right" field="year_budget" title="预算合计（万元）"></vxe-column>
        <vxe-column align="right" field="expense_amount" title="开支合计（万元）"></vxe-column>
        <vxe-column align="right" title="占比">
          <template #default="{ row }">
            <span>{{ calculateExpensePercentage(row.year_budget, row.expense_amount) }}</span>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
    <div v-if="activeName == 'year' && tableLoading">
      <vxe-table max-height="500" border resizable show-overflow :data="budgetList" size="mini" show-footer ref="hehaiyangRef"
        :footer-method="yearFooterMethod"
        :merge-footer-items="[{ row: 0, col: 0, rowspan: 0, colspan: 2 }, { row: 1, col: 0, rowspan: 0, colspan: 2 }]">
        <vxe-column type="seq" width="60"></vxe-column>
        <vxe-column align="left" field="class_funds" title="科目名称" width="120"></vxe-column>
        <vxe-column align="right" field="year_budget" title="预算合计（万元）" width="120">
          <template #default="{ row }">
            <span>{{ getYearTotal(row, 'budget') }}</span>
          </template>
        </vxe-column>
        <vxe-column align="right" field="year_expenses" title="开支合计（万元）" width="120">
          <template #default="{ row }">
            <span>{{ getYearTotal(row, 'expenses') }}</span>
          </template>
        </vxe-column>
        <vxe-colgroup v-for="(year, index) in periodList" :key="index" :title="year + '（万元）'" align="right">
          <vxe-column :field="`${year}-budget`" title="预算" max-width="120" align="right">
            <template #default="{ row }">
              <span v-if="row.data[year]">{{ row.data[year].budget }}</span>
            </template>
          </vxe-column>
          <vxe-column :field="`${year}-expenses`" title="开支" max-width="120" align="right">
            <template #default="{ row }">
              <span v-if="row.data[year]">{{ row.data[year].expenses }}</span>
            </template>
          </vxe-column>
        </vxe-colgroup>
      </vxe-table>
    </div>
    <div v-if="(activeName == 'quarter' || activeName == 'month') && tableLoading">
      <vxe-table max-height="500" border resizable show-overflow :data="budgetList" size="mini" show-footer
        :footer-method="quarterFooterMethod"
        :merge-footer-items="[{ row: 0, col: 0, rowspan: 0, colspan: 2 }, { row: 1, col: 0, rowspan: 0, colspan: 2 }]">
        <vxe-column type="seq" width="60"></vxe-column>
        <vxe-column align="left" field="class_funds" title="科目名称" width="120"></vxe-column>
        <vxe-column align="right" field="year_budget" title="预算合计（万元）" width="120"></vxe-column>
        <vxe-column align="right" field="expense_amount" title="开支合计（万元）" width="120"></vxe-column>
        <vxe-column v-for="(quarter, index) in periodList" :key="index" :field="`${quarter}`"
          :title="`${quarter}${activeName == 'quarter' ? '季度' : '月'}（万元）`" max-width="120" align="right"></vxe-column>
      </vxe-table>
    </div>
  </div>
</template> 
<script>

export default {
  name: "ProjectExpenses",
  data() {
    return {
      project_id: '',
      activeName: 'all',
      activeSource: 'XMJFLY_ZJF',
      sourceGroup: [{
        name: '总经费',
        key: 'XMJFLY_ZJF'
      }, {
        name: '纵向',
        key: 'XMJFLY_ZX'
      }, {
        name: '横向',
        key: 'XMJFLY_HX'
      }, {
        name: '自筹',
        key: 'XMJFLY_ZC'
      }],
      budget_from: [], // 来源
      budgetList: [], // 预算
      periodList: [], // 维度
      tableLoading: true
    }
  },
  mounted() {
    let urlParams = this.getUrlParams()
    this.project_id = urlParams.project_id
    this.init()
  },
  methods: {
    getUrlParams() {
      const params = {};
      const queryString = window.location.search.substring(1);
      const keyValuePairs = queryString.split('&');
      for (const pair of keyValuePairs) {
        const [key, value] = pair.split('=');
        params[decodeURIComponent(key)] = decodeURIComponent(value);
      }
      return params;
    },
    async init() {
      const { returnValue } = await window.systemService.callAutomatic({
        automaticId: 'cost_project_budget',
        args: [{
          project_id: this.project_id,
          source_id: this.activeSource,
          type: 'all'
        }]
      })
      console.log(123, returnValue)
      this.projectForm = returnValue
      this.budget_from = returnValue.budget_from // 来源
      this.budgetList = returnValue.budgetList
    },
    // 点击上面
    async handleClick() {
      this.activeSource = 'XMJFLY_ZJF'
      this.getBudgetData()
    },
    // 点击来源
    async sourceHandleClick(item) {
      this.activeSource = item.key
      this.getBudgetData()
    },
    // 获取列表
    async getBudgetData() {
      this.tableLoading = false
      const { returnValue } = await window.systemService.callAutomatic({
        automaticId: 'cost_project_budget',
        args: [{
          project_id: this.project_id,
          source_id: this.activeSource,
          type: this.activeName
        }]
      })
      this.budgetList = returnValue.budgetList // 经费 开支
      this.periodList = returnValue.periodList // 维度
      setTimeout(() => {
        this.tableLoading = true
      }, 10)
    },
    sumNum(list, field) {
      let count = 0
      list.forEach(item => {
        count += Number(item[field])
      })
      return count.toFixed(2)
    },
    footerMethod({ columns, data }) {
      const footerData = [
        columns.map((column, _columnIndex) => {
          if (_columnIndex === 0) {
            return '合计'
          }
          if (_columnIndex === 1) {
            return '合计'
          }
          if (['year_budget', 'expense_amount'].includes(column.field)) {
            return this.sumNum(data, column.field)
          }
          return this.calculateExpensePercentage(this.sumNum(data, 'year_budget'), this.sumNum(data, 'expense_amount'))
        })
      ]
      return footerData
    },
    // 年度
    getYearTotal(row, type) {
      let total = 0
      for (const key in row.data) {
        total += +row.data[key][type]
      }
      return total
    },
    yearFooterMethod({ columns, data }) {
      const footerData = [
        columns.map((column, _columnIndex) => {
          if (_columnIndex === 0 || _columnIndex === 1) {
            return '合计'
          }
          // 预算总合计、开支总合计
          if (column.field == 'year_budget' || column.field == 'year_expenses') {
            let fieldSplit = column.field.split('_')
            let total = 0
            data.forEach((item) => {
              for (const key in item.data) {
                total += +item.data[key][fieldSplit[1]]
              }
            })
            return total.toFixed(2)
          }
          // 预算合计、开支合计
          if (column.field && (column.field.includes('budget') || column.field.includes('expenses'))) {
            let fieldSplit = column.field.split('-')
            let total = 0
            data.forEach((item) => {
              if (item.data[fieldSplit[0]]) {
                total += +item.data[fieldSplit[0]][fieldSplit[1]]
              }
            })
            return total.toFixed(2)
          }
          return ''
        }),
        columns.map((column, _columnIndex) => {
          if (_columnIndex === 0 || _columnIndex === 1) {
            return '占比'
          }
          // 总占比
          if (column.field == 'year_expenses') {
            let budgetTotal = 0
            let expensesTotal = 0
            data.forEach((item) => {
              for (const key in item.data) {
                budgetTotal += +item.data[key]['budget']
                expensesTotal += +item.data[key]['expenses']
              }
            })
            return this.calculateExpensePercentage(budgetTotal, expensesTotal)
          }
          // 年度占比
          if (column.field && column.field.includes('expenses')) {
            let fieldSplit = column.field.split('-')
            let budgetTotal = 0
            let expensesTotal = 0
            data.forEach((item) => {
              if (item.data[fieldSplit[0]]) {
                budgetTotal += +item.data[fieldSplit[0]]['budget']
                expensesTotal += +item.data[fieldSplit[0]]['expenses']
              } else {
                // console.log(item)
              }
            })
            return this.calculateExpensePercentage(budgetTotal, expensesTotal)
          }
          return ''
        })
      ]
      return footerData
    },
    // 季度
    quarterFooterMethod({ columns, data }) {
      // data
      const footerData = [
        columns.map((column, _columnIndex) => {
          if (_columnIndex === 0 || _columnIndex === 1) {
            return '合计'
          }
          if (['year_budget', 'expense_amount', ...this.periodList].includes(column.field)) {
            return this.sumNum(data, column.field)
          }
          return ''
        }),
        columns.map((column, _columnIndex) => {
          if (_columnIndex === 0 || _columnIndex === 1) {
            return '占比'
          }
          // 总占比
          if (column.field == 'expense_amount') {
            return this.calculateExpensePercentage(this.sumNum(data, 'year_budget'), this.sumNum(data, 'expense_amount'))
          }
          return ''
        })
      ]
      return footerData
    },
    calculateExpensePercentage(budget, expense) {
      if (!expense || expense == '0.00') {
        return '0%'
      }
      if (!budget || budget == '0.00') {
        return ''
      }
      const percentage = (expense / budget) * 100
      return `${percentage.toFixed(0)}%`
    }
  },
}
</script>
<style scoped>
.gy-view {
  background: #fff;
  height: 100%;
}
.project-expenses {
  padding: 0 20px;
}

.source-group {
  display: flex;
  background: #f5f4f6;
  width: fit-content;
  border-radius: 20px 20px 20px 20px;
  margin-bottom: 20px;
}

.source-group div {
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 85px;
  height: 30px;
  border-radius: 24px 24px 24px 24px;
  opacity: 1;
  font-weight: 400;
  color: #5f6165;
  font-size: 12px;
}

.is-active {
  background: #347ae9;
  color: #ffffff !important;
}

.title {
  margin: 10px 0;
}
</style>